﻿<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据输入表单</title>

    <style>
        /* 样式部分保持不变 */
        body {
            font-family: 'Inter', system-ui, sans-serif;
            background-color: #f9fafb;
            min-height: 100vh;
        }

        .completed-number-header {
            background-color: #f0fdf4;
            color: #065f46;
            font-size: 0.75rem;
        }

        .completed-number-cell {
            background-color: #f0fdf4;
            color: #065f46;
            font-weight: 500;
            padding: 0.25rem;
            border-radius: 0.25rem;
            margin-top: 0.25rem;
        }

        .container {
            width: 95%;
            margin: 0 auto;
            padding: 2rem;
        }

        .form-card {
            background-color: white;
            border-radius: 0.5rem;
            box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
            padding: 1.5rem;
        }

        .form-title {
            font-size: 1.25rem;
            font-weight: 600;
            color: #1f2937;
            margin-bottom: 1.5rem;
        }

        .form-group {
            margin-bottom: 1rem;
        }

        .form-label {
            display: block;
            font-size: 0.875rem;
            font-weight: 500;
            color: #4b5563;
            margin-bottom: 0.25rem;
        }

        .text-red-500 {
            color: #ef4444;
        }

        .form-input {
            width: 100%;
            padding: 0.5rem 0.75rem;
            border: 1px solid #d1d5db;
            border-radius: 0.375rem;
            font-size: 1rem;
        }

            .form-input:focus {
                outline: none;
                border-color: #6366f1;
                box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.2);
            }

            .form-input.readonly {
                background-color: #f3f4f6;
                cursor: not-allowed;
            }

        .grid-cols-2 {
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr));
            gap: 1.5rem;
        }

        .matrix-container {
            margin-bottom: 1.5rem;
            overflow-x: auto;
        }

        .matrix-table {
            width: 100%;
            border-collapse: collapse;
        }

            .matrix-table th,
            .matrix-table td {
                padding: 0.25rem 0.5rem;
                border: 1px solid #d1d5db;
                text-align: center;
            }

        .date-header-content {
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .date-label {
            padding: 0.25rem;
            background-color: #f3f4f6;
            font-size: 0.75rem;
            font-weight: 500;
            color: #4b5563;
            width: 100%;
            box-sizing: border-box;
        }

        .real-number-header {
            background-color: #fef2f2;
            color: #b91c1c;
            font-size: 0.75rem;
        }

        .plan-number-header {
            background-color: #eff6ff;
            color: #1e40af;
            font-size: 0.75rem;
        }

        .matrix-table th {
            background-color: #f3f4f6;
            font-size: 0.875rem;
            font-weight: 500;
            color: #4b5563;
        }

        .matrix-table td:first-child {
            font-weight: 500;
            background-color: #f9fafb;
        }

        .matrix-input {
            width: 100%;
            text-align: center;
            padding: 0.25rem 0;
            border: none;
            font-size: 0.875rem;
        }

            .matrix-input:focus {
                outline: none;
                background-color: #f3f4f6;
            }

        .real-number-input {
            background-color: #fef2f2;
        }

        .matrix-input:disabled {
            background-color: #f3f4f6;
            color: #6b7280;
            cursor: not-allowed;
        }

        .plan-number-input {
            background-color: #eff6ff;
        }

        .btn-group {
            display: flex;
            justify-content: flex-end;
            gap: 0.75rem;
        }

        .btn {
            padding: 0.5rem 1rem;
            border-radius: 0.375rem;
            font-size: 0.875rem;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .btn-reset {
            background-color: white;
            color: #4b5563;
            border: 1px solid #d1d5db;
        }

            .btn-reset:hover {
                background-color: #f9fafb;
            }

        .btn-save {
            background-color: #6366f1;
            color: white;
            border: none;
        }

            .btn-save:hover {
                background-color: #4f46e5;
            }

        .date-picker {
            font-size: 0.875rem;
            border: none;
            background-color: transparent;
            outline: none;
            width: 100%;
        }

        /* 加载动画 */
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(255, 255, 255, 0.7);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
            opacity: 0;
            visibility: hidden;
            transition: opacity 0.3s ease, visibility 0.3s ease;
        }

            .loading-overlay.active {
                opacity: 1;
                visibility: visible;
            }

        .spinner {
            width: 40px;
            height: 40px;
            border: 4px solid rgba(99, 102, 241, 0.2);
            border-radius: 50%;
            border-top-color: #6366f1;
            animation: spin 1s ease-in-out infinite;
        }

        @@keyframes spin {
            to

        {
            transform: rotate(360deg);
        }

        }

        /* 提示信息 */
        .toast {
            position: fixed;
            bottom: 20px;
            right: 20px;
            padding: 12px 20px;
            border-radius: 4px;
            background-color: #10b981;
            color: white;
            font-size: 0.875rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
            opacity: 0;
            visibility: hidden;
            transition: opacity 0.3s ease, visibility 0.3s ease, transform 0.3s ease;
            transform: translateY(20px);
            z-index: 1001;
        }

            .toast.error {
                background-color: #ef4444;
            }

            .toast.active {
                opacity: 1;
                visibility: visible;
                transform: translateY(0);
            }
    </style>
</head>
<body>
    <!-- 加载动画 -->
    <div id="loadingOverlay" class="loading-overlay">
        <div class="spinner"></div>
    </div>

    <!-- 提示信息 -->
    <div id="toast" class="toast">操作成功</div>

    <div class="container">
        <div class="form-card">
            <!-- 表单标题 -->
            <h1 class="form-title">数据输入表单</h1>

            <!-- 单行输入区 - 包含新增字段 -->
            <div class="grid-cols-2 mb-6">
                <div class="form-group">
                    <label for="input1" class="form-label">工令号 <span class="text-red-500">*</span></label>
                    <input type="text" id="input1" class="form-input" placeholder="请输入数字工令号" required>
                </div>
                <div class="form-group">
                    <label for="customerOrderId" class="form-label">客户订单号</label>
                    <input type="text" id="customerOrderId" class="form-input readonly" placeholder="请输入客户订单号" readonly>
                </div>
                <div class="form-group">
                    <label for="customer" class="form-label">客户名称</label>
                    <input type="text" id="customer" class="form-input readonly" placeholder="请输入客户名称" readonly>
                </div>
                <div class="form-group">
                    <label for="projectName" class="form-label">项目名称</label>
                    <input type="text" id="projectName" class="form-input readonly" placeholder="请输入项目名称" readonly>
                </div>
                <div class="form-group">
                    <label for="deliveryDate" class="form-label">交货日期</label>
                    <input type="date" id="deliveryDate" class="form-input readonly" readonly>
                </div>
                <div class="form-group">
                    <label for="productOrder" class="form-label">产品型号</label>
                    <input type="text" id="productOrder" class="form-input readonly" placeholder="请输入产品型号" readonly>
                </div>
                <div class="form-group">
                    <label for="orderNumber" class="form-label">订单数量</label>
                    <input type="number" id="orderNumber" class="form-input readonly" placeholder="请输入订单数量" min="1" readonly>
                </div>
            </div>

            <!-- 矩阵输入区 -->
            <div class="mb-6">
                <label class="form-label block mb-2">矩阵数据</label>
                <div class="matrix-container">
                    <table class="matrix-table">
                        <thead>
                            <tr>
                                <th class="matrix-header" rowspan="2">日期/工序</th>
                                @* <th class="matrix-header" rowspan="2">
                                    <span id="totalQuantityHeader">总数量：加载中...（下列显示各工序完工数量）</span>
                                </th> *@
                                <th class="matrix-header" colspan="2">
                                    <div class="date-header-content">
                                        <div class="date-label">
                                            <input type="date" id="startDate" class="date-picker">
                                        </div>
                                    </div>
                                </th>
                                <th class="matrix-header" colspan="2">
                                    <div class="date-header-content">
                                        <div class="date-label"/>
                                    </div>
                                </th>
                                <th class="matrix-header" colspan="2">
                                    <div class="date-header-content">
                                        <div class="date-label"/>
                                    </div>
                                </th>
                                <th class="matrix-header" colspan="2">
                                    <div class="date-header-content">
                                        <div class="date-label"/>
                                    </div>
                                </th>
                                <th class="matrix-header" colspan="2">
                                    <div class="date-header-content">
                                        <div class="date-label"/>
                                    </div>
                                </th>
                                <th class="matrix-header" colspan="2">
                                    <div class="date-header-content">
                                        <div class="date-label"/>
                                    </div>
                                </th>
                                <th class="matrix-header" colspan="2">
                                    <div class="date-header-content">
                                        <div class="date-label"/>
                                    </div>
                                </th>
                                <th class="matrix-header" colspan="2">
                                    <div class="date-header-content">
                                        <div class="date-label" />
                                    </div>
                                </th>
                                <th class="matrix-header" colspan="2">
                                    <div class="date-header-content">
                                        <div class="date-label" />
                                    </div>
                                </th>
                                <th class="matrix-header" colspan="2">
                                    <div class="date-header-content">
                                        <div class="date-label" />
                                    </div>
                                </th>
                            </tr>
                            <tr>
                                <th class="matrix-header plan-number-header">计划</th>
                                <th class="matrix-header real-number-header">实际</th>
                                <th class="matrix-header plan-number-header">计划</th>
                                <th class="matrix-header real-number-header">实际</th>
                                <th class="matrix-header plan-number-header">计划</th>
                                <th class="matrix-header real-number-header">实际</th>
                                <th class="matrix-header plan-number-header">计划</th>
                                <th class="matrix-header real-number-header">实际</th>
                                <th class="matrix-header plan-number-header">计划</th>
                                <th class="matrix-header real-number-header">实际</th>
                                <th class="matrix-header plan-number-header">计划</th>
                                <th class="matrix-header real-number-header">实际</th>
                                <th class="matrix-header plan-number-header">计划</th>
                                <th class="matrix-header real-number-header">实际</th>
                                <th class="matrix-header plan-number-header">计划</th>
                                <th class="matrix-header real-number-header">实际</th>
                                <th class="matrix-header plan-number-header">计划</th>
                                <th class="matrix-header real-number-header">实际</th>
                                <th class="matrix-header plan-number-header">计划</th>
                                <th class="matrix-header real-number-header">实际</th>
                            </tr>
                        </thead>
                        <tbody id="matrixBody">
                            <tr>
                                <td colspan="15" class="text-center py-4 text-gray-500">加载中...</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- 操作按钮 -->
            <div class="btn-group">
                <button id="resetBtn" class="btn btn-reset">重置</button>
                <button id="saveBtn" class="btn btn-save">保存</button>
            </div>
        </div>
    </div>

    <script>
        // 日期格式化函数 - 显示格式
        function formatDateDisplay(date) {
            const year = date.getFullYear();
            const month = (date.getMonth() + 1).toString().padStart(2, '0');
            const day = date.getDate().toString().padStart(2, '0');
            return `${year}年${month}月${day}日`;
        }

        // 日期格式化函数 - 数据格式 (YYYY-MM-DD)
        function formatDateData(date) {
            const year = date.getFullYear();
            const month = (date.getMonth() + 1).toString().padStart(2, '0');
            const day = date.getDate().toString().padStart(2, '0');
            return `${year}-${month}-${day}`;
        }

        // 获取指定日期之后的第n天
        function getNextDay(date, days) {
            const result = new Date(date);
            result.setDate(result.getDate() + days);
            return result;
        }

        // 防抖函数
        function debounce(func, wait) {
            let timeout;
            return function executedFunction(...args) {
                const later = () => {
                    clearTimeout(timeout);
                    func(...args);
                };
                clearTimeout(timeout);
                timeout = setTimeout(later, wait);
            };
        }

        // 显示加载动画
        function showLoading() {
            document.getElementById('loadingOverlay').classList.add('active');
        }

        // 隐藏加载动画
        function hideLoading() {
            document.getElementById('loadingOverlay').classList.remove('active');
        }

        // 显示提示信息
        function showToast(message, isError = false) {
            const toast = document.getElementById('toast');
            toast.textContent = message;
            toast.className = isError ? 'toast error active' : 'toast active';
            setTimeout(() => toast.classList.remove('active'), 3000);
        }

        // 处理数值显示，-1显示为"-"
        function formatDisplayValue(value) {
            if (value === -1 || value === null || value === undefined || value === 'null' || value === '-1') {
                return '-';
            }
            if (!isNaN(value)) {
                return value;
            }
            return value;
        }

        // 处理数值存储，"-"转换为-1
        function formatStorageValue(value) {
            if (value === '-' || value === '' || value === null || value === undefined) {
                return -1;
            }
            if (!isNaN(value)) {
                return parseInt(value);
            }
            return value;
        }

        //此段代码由于时效性暂时隐藏
        // 生成工序完成量数据
        // function getProcessCompletedQuantities(processIds, workOrderNumber) {
        //     const result = [];
        //     if (!processIds || processIds.length === 0) return result;

        //     showLoading(); 发起请求前显示加载框
        //     return fetch('/PMCManage/Schedule/GetProcessCompletedQuantities', {
        //         method: 'POST',
        //         headers: { 'Content-Type': 'application/json' },
        //         credentials: 'include',
        //         body: JSON.stringify({ workOrderNumber, processIds })
        //     })
        //     .then(response => {
        //         if (!response.ok) throw new Error(`HTTP错误！状态码：${response.status}`);
        //         return response.json();
        //     })
        //     .then(result => result)
        //     .catch(error => {
        //         console.error('获取工序完成量失败：', error);
        //         throw error;
        //     })
        //     .finally(() => {
        //         hideLoading(); 请求完成后隐藏加载框
        //     });
        // }

        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', function() {
            // 全局变量
            let processList = []; // 工序列表
            let currentWorkOrder = ''; // 当前工令号
            let currentOrderQuantity = 0; // 当前订单总数量
            let processCompletedQuantities = []; // 工序完成量数组
            // 新增：缓存工令完整信息（避免重复请求）
            let currentWorkOrderInfo = null;

            // 从后端获取工序信息
            async function getProcessListFromBackend() {
                try {
                    showLoading(); // 发起请求前显示加载框
                    const response = await fetch('/PMCManage/Process/GetListJsonByDepartmentRemark', {
                        method: 'GET',
                        headers: { 'Content-Type': 'application/json' },
                        credentials: 'include'
                    });
                    if (!response.ok) throw new Error(`HTTP错误！状态码：${response.status}`);
                    const data = await response.json();
                    return Array.isArray(data) ? data : (data?.Data && Array.isArray(data.Data) ? data.Data : []);
                } catch (error) {
                    throw error;
                } finally {
                    hideLoading(); // 请求完成后隐藏加载框
                }
            }

            // 合并请求：一次获取工令的完整信息（基础信息+订单数量）
            async function getWorkOrderFullInfo(workOrderNumber) {
                try {
                    showLoading(); // 发起请求前显示加载框
                    const response = await fetch('/PMCManage/Schedule/GetListJson', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        credentials: 'include',
                        body: JSON.stringify({
                            workOrderNumber: workOrderNumber,
                            fetchFirst: true // 只取第一条数据
                        })
                    });

                    if (!response.ok) throw new Error(`获取工令信息失败，状态码：${response.status}`);
                    const data = await response.json();
                    const workOrderInfo = data[0] || {};
                    // 缓存信息，避免重复请求
                    currentWorkOrderInfo = workOrderInfo;
                    return workOrderInfo;
                } catch (error) {
                    console.error('获取工令信息失败：', error);
                    currentWorkOrderInfo = null; // 失败时清空缓存
                    return {};
                } finally {
                    hideLoading(); // 请求完成后隐藏加载框
                }
            }

            //由于时效性隐藏
            // 根据工令号获取订单总数量（复用完整信息）
            // async function getOrderQuantityByWorkOrder(workOrderNumber) {
            //     如果已有缓存，直接使用缓存数据
            //     if (currentWorkOrderInfo) {
            //         return currentWorkOrderInfo.OrderNumber || 0;
            //     }
            //     无缓存则调用接口获取
            //     const workOrderInfo = await getWorkOrderFullInfo(workOrderNumber);
            //     return workOrderInfo.OrderNumber || 0;
            // }

            //由于时效性隐藏
            // 根据工令号获取工序完成量
            // function getProcessCompletedQuantitiesByWorkOrder(workOrderNumber) {
            //     const processIds = processList.map(process => process.Id);
            //     return getProcessCompletedQuantities(processIds, workOrderNumber);
            // }

            // 根据工令号和日期获取计划数据
            async function getPlanDataByWorkOrder(workOrderNumber, startDate, length = 10) {
                try {
                    showLoading();
                    const processIds = processList.map(process => process.Id);
                    const params = { workOrderNumber, startDate: formatDateData(startDate), length, processIds };
                    const response = await fetch('/PMCManage/Schedule/GetPlanData', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        credentials: 'include',
                        body: JSON.stringify(params)
                    });
                    if (!response.ok) throw new Error(`HTTP错误！状态码：${response.status}`);
                    return await response.json();
                } catch (error) {
                    showToast('获取计划数据失败，请稍后重试', true);
                    throw error;
                } finally {
                    hideLoading();
                }
            }

            // 获取DOM元素
            const matrixBody = document.getElementById('matrixBody');
            const startDateInput = document.getElementById('startDate');
            const resetBtn = document.getElementById('resetBtn');
            const saveBtn = document.getElementById('saveBtn');
            const input1 = document.getElementById('input1');
            const totalQuantityHeader = document.getElementById('totalQuantityHeader');
            // 新增字段DOM元素
            const customerOrderId = document.getElementById('customerOrderId');
            const customer = document.getElementById('customer');
            const projectName = document.getElementById('projectName');
            const deliveryDate = document.getElementById('deliveryDate');
            const productOrder = document.getElementById('productOrder');
            const orderNumber = document.getElementById('orderNumber');

            // 工令号输入框限制只能输入数字
            input1.addEventListener('keypress', function(e) {
                const char = e.key;
                if (!/^\d$/.test(char) && !e.ctrlKey && !e.metaKey) {
                    e.preventDefault();
                }
            });

            // 工令号输入框失去焦点时验证
            input1.addEventListener('blur', function() {
                const value = this.value.trim();
                if (value && !/^\d+$/.test(value)) {
                    showToast('工令号只能包含数字！', true);
                    this.value = '';
                    this.focus();
                }
            });

            // 动态生成工序行
            function generateProcessRows(processes) {
                matrixBody.innerHTML = '';
                processes.forEach((process, rowIndex) => {
                    const row = document.createElement('tr');

                    // 工序名称单元格
                    const nameCell = document.createElement('td');
                    nameCell.className = 'matrix-cell font-medium';
                    nameCell.textContent = process.Name;
                    nameCell.setAttribute('data-process-id', process.Id);
                    nameCell.setAttribute('title', process.Description || '');
                    row.appendChild(nameCell);

                    //由于时效性隐藏
                    // 已完工数量单元格
                    // const completedCell = document.createElement('td');
                    // completedCell.className = 'matrix-cell completed-number-cell';
                    // completedCell.textContent = '-';
                    // completedCell.setAttribute('data-process-id', process.Id);
                    // completedCell.setAttribute('data-row', rowIndex);
                    // row.appendChild(completedCell);

                    // 创建10个日期列（计划+实际产量）
                    for (let colIndex = 0; colIndex < 10; colIndex++) {
                        // 计划产量输入框
                        const planCell = document.createElement('td');
                        planCell.className = 'matrix-cell';
                        const planInput = document.createElement('input');
                        planInput.type = 'text';
                        planInput.className = 'matrix-input plan-number-input';
                        planInput.value = '-';
                        planInput.setAttribute('data-row', rowIndex);
                        planInput.setAttribute('data-col', colIndex);
                        planInput.setAttribute('data-type', 'plan');
                        planInput.setAttribute('data-process-id', process.Id);
                        planInput.addEventListener('focus', handleInputFocus);
                        planInput.addEventListener('blur', handleInputBlur);
                        planInput.addEventListener('keypress', handleInputKeypress);
                        planCell.appendChild(planInput);
                        row.appendChild(planCell);

                        // 实际产量输入框
                        const realCell = document.createElement('td');
                        realCell.className = 'matrix-cell';
                        const realInput = document.createElement('input');
                        realInput.type = 'text';
                        realInput.className = 'matrix-input real-number-input';
                        realInput.value = '-';
                        realInput.setAttribute('data-row', rowIndex);
                        realInput.setAttribute('data-col', colIndex);
                        realInput.setAttribute('data-type', 'real');
                        realInput.setAttribute('data-process-id', process.Id);
                        realInput.disabled = true;
                        realCell.appendChild(realInput);
                        row.appendChild(realCell);
                    }

                    matrixBody.appendChild(row);
                });
            }

            // 由于时效性隐藏
            // 更新总数量显示
            // function updateTotalQuantityDisplay(quantity) {
            //     totalQuantityHeader.textContent = quantity > 0
            //         ? `总数量：${quantity}台（下列显示各工序完工数量）`
            //         : '当前销售订单未录入过系统';
            // }

            //由于时效性隐藏
            // 更新工序完成量显示
            // function updateProcessCompletedQuantitiesDisplay(completedQuantities) {
            //     const completedCells = document.querySelectorAll('.completed-number-cell');
            //     completedCells.forEach(cell => cell.textContent = '-');
            //     if (!completedQuantities || !Array.isArray(completedQuantities) || completedQuantities.length === 0) {
            //         return;
            //     }
            //     completedQuantities.forEach(completed => {
            //         const processId = completed.processId;
            //         const quantity = completed.completedQuantity;
            //         const cell = document.querySelector(`.completed-number-cell[data-process-id="${processId}"]`);
            //         if (cell && quantity > 0) {
            //             cell.textContent = quantity;
            //         }
            //     });
            // }

            // 设置矩阵数据
            function setMatrixData(planData) {
                const matrixInputs = document.querySelectorAll('.matrix-input');
                matrixInputs.forEach(input => input.value = '-');
                if (!planData || !Array.isArray(planData)) return;

                planData.forEach(plan => {
                    try {
                        const startDate = new Date(startDateInput.value);
                        startDate.setHours(0, 0, 0, 0);
                        const planDate = new Date(plan.Date);
                        planDate.setHours(0, 0, 0, 0);
                        const dayDiff = Math.floor((planDate - startDate) / (1000 * 3600 * 24));

                        if (dayDiff >= 0 && dayDiff < 10) {
                            const planInputs = document.querySelectorAll(`.matrix-input[data-process-id="${plan.ProcessId}"][data-type="plan"]`);
                            if (planInputs.length > 0 && planInputs[dayDiff]) {
                                planInputs[dayDiff].value = formatDisplayValue(plan.PlanNumber);
                            }
                            const realInputs = document.querySelectorAll(`.matrix-input[data-process-id="${plan.ProcessId}"][data-type="real"]`);
                            if (realInputs.length > 0 && realInputs[dayDiff]) {
                                realInputs[dayDiff].value = formatDisplayValue(plan.RealNumber);
                            }
                        }
                    } catch (error) {
                        console.error(`处理计划数据时出错: ${error.message}`, plan);
                    }
                });
            }

            // 更新日期表头
            function updateDateHeaders(startDate) {
                const dateLabels = document.querySelectorAll('.date-label');
                dateLabels.forEach((label, index) => {
                    const currentDate = getNextDay(startDate, index);
                    label.setAttribute('data-date', formatDateData(currentDate));
                    if (index > 0) {
                        label.textContent = formatDateDisplay(currentDate);
                    }
                });
            }

            // 根据工令号和日期加载数据
            async function loadDataByWorkOrderAndDate(workOrderNumber, startDate) {
                try {
                    if (processList.length === 0) {
                        processList = await getProcessListFromBackend();
                        generateProcessRows(processList);
                    }

                    // if (workOrderNumber) {
                    //     try {
                    //         复用完整信息中的订单数量
                    //         currentOrderQuantity = await getOrderQuantityByWorkOrder(workOrderNumber);
                    //         updateTotalQuantityDisplay(currentOrderQuantity);
                    //     } catch (error) {
                    //         currentOrderQuantity = 0;
                    //         updateTotalQuantityDisplay(0);
                    //         showToast('获取订单总数量失败，请稍后重试', true);
                    //     }

                    //     processCompletedQuantities = await getProcessCompletedQuantitiesByWorkOrder(workOrderNumber);
                    //     updateProcessCompletedQuantitiesDisplay(processCompletedQuantities);
                    // } else {
                    //     currentOrderQuantity = 0;
                    //     updateTotalQuantityDisplay(0);
                    //     updateProcessCompletedQuantitiesDisplay([]);
                    // }

                    if (!workOrderNumber) {
                        setMatrixData([]);
                        return;
                    }

                    const planData = await getPlanDataByWorkOrder(workOrderNumber, startDate);
                    setMatrixData(planData);
                    showToast('数据加载成功');
                } catch (error) {
                    console.log(error);
                    showToast('加载数据失败，请稍后重试', true);
                }
            }

            // 防抖处理的加载数据函数
            const debouncedLoadData = debounce(async function(workOrderNumber, startDate) {
                await loadDataByWorkOrderAndDate(workOrderNumber, startDate);
            }, 500);

            // 工令号输入事件（复用完整信息填充表单）
            input1.addEventListener('input', async function() {
                const value = this.value.trim();
                currentWorkOrder = value;
                // 清空缓存（工令号变化时）
                currentWorkOrderInfo = null;

                if (value && /^\d+$/.test(value)) {
                    const startDate = new Date(startDateInput.value);
                    // 1. 加载排产数据（原有逻辑）
                    debouncedLoadData(value, startDate);

                    // 2. 获取工令完整信息并填充表单（仅一次请求）
                    const workOrderInfo = await getWorkOrderFullInfo(value);
                    // 填充字段（处理日期格式）
                    customerOrderId.value = workOrderInfo.CustomerOrderId || '';
                    customer.value = workOrderInfo.Customer || '';
                    projectName.value = workOrderInfo.ProjectName || '';
                    // 处理日期格式：提取YYYY-MM-DD部分（去掉T及后面的内容）
                    const rawDeliveryDate = workOrderInfo.DeliveryDate || '';
                    deliveryDate.value = rawDeliveryDate ? rawDeliveryDate.split('T')[0] : '';
                    productOrder.value = workOrderInfo.ProductOrder || '';
                    orderNumber.value = workOrderInfo.OrderNumber || '';
                } else if (value === '') {
                    // 清空工令号时，同步清空基础信息输入框
                    customerOrderId.value = '';
                    customer.value = '';
                    projectName.value = '';
                    deliveryDate.value = '';
                    productOrder.value = '';
                    orderNumber.value = '';

                    // 原有逻辑：清空表格数据
                    setMatrixData([]);
                    //updateTotalQuantityDisplay(0);
                    //updateProcessCompletedQuantitiesDisplay([]);
                }
            });

            // 日期选择器变更事件
            startDateInput.addEventListener('change', async function() {
                const selectedDate = new Date(this.value);
                if (!isNaN(selectedDate.getTime())) {
                    updateDateHeaders(selectedDate);
                    if (currentWorkOrder) {
                        await loadDataByWorkOrderAndDate(currentWorkOrder, selectedDate);
                    }
                }
            });

            // 重置按钮点击事件
            resetBtn.addEventListener('click', function() {
                // 重置所有输入框（包含新增字段）
                input1.value = '';
                customerOrderId.value = '';
                customer.value = '';
                projectName.value = '';
                deliveryDate.value = '';
                productOrder.value = '';
                orderNumber.value = '';

                // 重置全局变量和缓存
                currentWorkOrder = '';
                //currentOrderQuantity = 0;
                //processCompletedQuantities = [];
                currentWorkOrderInfo = null;

                // 重置矩阵输入框
                const matrixInputs = document.querySelectorAll('.matrix-input');
                matrixInputs.forEach(input => input.value = '-');

                // 重置显示
                //updateTotalQuantityDisplay(0);
                //updateProcessCompletedQuantitiesDisplay([]);
                showToast('表单已重置！');
            });

            // 保存按钮点击事件
            saveBtn.addEventListener('click', async function() {
                // 获取所有输入框的值（包含新增字段）
                const input1Value = input1.value.trim();
                const customerOrderIdValue = customerOrderId.value.trim();
                const customerValue = customer.value.trim();
                const projectNameValue = projectName.value.trim();
                const deliveryDateValue = deliveryDate.value;
                const productOrderValue = productOrder.value.trim();
                const orderNumberValue = orderNumber.value ? parseInt(orderNumber.value) : null;

                // 验证工令号
                if (!input1Value) {
                    showToast('请填写工令号！', true);
                    input1.focus();
                    return;
                }
                if (!/^\d+$/.test(input1Value)) {
                    showToast('工令号只能包含数字！', true);
                    input1.focus();
                    return;
                }

                // 收集矩阵数据
                const processRows = document.querySelectorAll('#matrixBody tr');
                const startDate = new Date(startDateInput.value);
                const outputData = [];

                processRows.forEach((row) => {
                    const nameCell = row.querySelector('td:first-child');
                    const processId = nameCell?.getAttribute('data-process-id');
                    if (!processId) return;

                    const inputs = row.querySelectorAll('.matrix-input');
                    for (let colIndex = 0; colIndex < 10; colIndex++) {
                        const realInput = inputs[colIndex * 2 + 1];
                        const planInput = inputs[colIndex * 2];
                        const realValue = realInput ? realInput.value.trim() : '-';
                        const planValue = planInput ? planInput.value.trim() : '-';

                        if (realValue !== '-' || planValue !== '-') {
                            const currentDate = getNextDay(startDate, colIndex);
                            const formattedDate = formatDateData(currentDate);
                            outputData.push({
                                Date: formattedDate,
                                ProcessId: processId,
                                WorkOrderNumber: input1Value,
                                PlanNumber: formatStorageValue(planValue),
                                RealNumber: formatStorageValue(realValue),
                                // 包含新增字段
                                CustomerOrderId: customerOrderIdValue,
                                Customer: customerValue,
                                ProjectName: projectNameValue,
                                DeliveryDate: deliveryDateValue || null,
                                ProductOrder: productOrderValue,
                                OrderNumber: orderNumberValue || 0
                            });
                        }
                    }
                });

                if (outputData.length === 0) {
                    showToast('没有数据需要保存！', true);
                    return;
                }

                try {
                    await sendDataToBackend(outputData);
                    showToast(`表单数据已保存！共收集到 ${outputData.length} 条有效数据。`);
                } catch (error) {
                    showToast('保存数据失败，请稍后重试', true);
                }
            });

            // 发送数据到后端
            function sendDataToBackend(data) {
                showLoading(); // 发起请求前显示加载框
                return fetch('/PMCManage/Schedule/InsertOrUpdateSchedule', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    credentials: 'include',
                    body: JSON.stringify(data)
                })
                .then(response => {
                    if (!response.ok) throw new Error(`HTTP错误！状态码：${response.status}`);
                    return response.json();
                })
                .catch(error => {
                    throw error;
                })
                .finally(() => {
                    hideLoading(); // 请求完成后隐藏加载框
                });
            }

            // 矩阵输入框事件处理
            function handleInputFocus() {
                if (this.value === '-') this.value = '';
            }
            function handleInputBlur() {
                if (this.value.trim() === '') this.value = '-';
            }
            function handleInputKeypress(e) {
                const char = e.key;
                if (!/^\d$/.test(char) && char !== '-' && !e.ctrlKey && !e.metaKey) {
                    e.preventDefault();
                }
            }

            // 初始化页面
            async function initializePage() {
                try {
                    const today = new Date();
                    const formattedToday = today.toISOString().split('T')[0];
                    startDateInput.value = formattedToday;
                    updateDateHeaders(today);

                    processList = await getProcessListFromBackend();
                    if (processList.length > 0) {
                        generateProcessRows(processList);
                        // updateTotalQuantityDisplay(0);
                    } else {
                        matrixBody.innerHTML = '<tr><td colspan="15" class="text-center py-4 text-gray-500">暂无工序数据</td></tr>';
                        // totalQuantityHeader.textContent = '总数量：0台（暂无工序数据）';
                    }
                } catch (error) {
                    matrixBody.innerHTML = '<tr><td colspan="15" class="text-center py-4 text-gray-500">获取工序数据失败，请稍后重试</td></tr>';
                    // totalQuantityHeader.textContent = '总数量：0台（获取工序数据失败）';
                    showToast('初始化页面失败，请刷新页面重试', true);
                }
            }

            // 初始化页面
            initializePage();
        });
    </script>
</body>
</html>
